package cn.qrx.gateway.executor;

import cn.qrx.gateway.datasource.Connection;
import cn.qrx.gateway.executor.result.GatewayResult;
import cn.qrx.gateway.mapping.HttpStatement;
import cn.qrx.gateway.seesion.Configuration;
import cn.qrx.gateway.type.SimpleTypeRegistry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.Map;

/**
 * @Author: 屈燃希
 * @Date: 2025/10/27
 * @Version: V1.0
 * @Description:
 */
public abstract class BaseExecutor implements  Executor{


    private Logger logger = LoggerFactory.getLogger(BaseExecutor.class);

    protected Configuration configuration;

    protected Connection connection;

    public BaseExecutor(Configuration configuration, Connection connection) {
        this.configuration = configuration;
        this.connection = connection;
    }

    @Override
    public GatewayResult execute(HttpStatement httpStatement, Map<String, Object> params) {

        String methodName = httpStatement.getMethodName();
        String parameterType =httpStatement.getParameterType();

        String[] parameterTypes = new String[]{parameterType};
        Object[]args = SimpleTypeRegistry.isSimpleType(parameterType)?params.values().toArray():new Object[]{params};
        logger.info("执行方法：{} #{}({}) args:{}",
                httpStatement.getApplication(),httpStatement.getMethodName(),httpStatement.getParameterType(),args);
        try {
            Object data = doExecute(methodName, parameterTypes, args);
            return GatewayResult.buildSuccess(data);
        } catch (Exception e) {
            return GatewayResult.buildError(e.getMessage());
        }

    }

    protected abstract Object doExecute(String methodName, String[] parameterTypes, Object[] args);
}
